import { BasicColumn } from '/@/components/Table';
import { FormSchema } from '/@/components/Table';
import { GoodsItem } from '../components/GoodsItem';
import { Buyer } from '../components/Buyer';
import { h } from 'vue';
import { Input, Popconfirm, Select, Tabs, Tag } from 'ant-design-vue';
const InputGroup = Input.Group;
const TabPane = Tabs.TabPane;
import {
  PayTypeEnum,
  PayTypeColorEnum,
  DeliveryTypeEnum,
  PayStatusEnum,
  OrderStatusEnum,
  ThirdDeliverStatusEnum,
  DeliveryStatusEnum,
  ReceiptStatusEnum,
  OrderSourceEnum,
} from '/@/common/enum/order';
import { storeDetail } from '/@/api/store';
import { updatePrint } from '/@/api/order/event';
let reload = () => {};
// table表格 数据
export const columns: BasicColumn[] = [
  {
    title: '订单',
    dataIndex: 'order_no',
    width: 100,
    customRender: ({ record }) => {
      if (!Reflect.has(record, 'pendingStatus')) {
        record.pendingStatus = false;
      }
      // jsx方式
      return <div onClick={(e) => e.stopPropagation()}>{record.order_no}</div>;
    },
  },
  {
    title: '商品',
    dataIndex: 'goods',
    slots: { title: 'customGoods', customRender: 'goods' },
    width: 100,
    customRender: ({ record }) => {
      if (!Reflect.has(record, 'pendingStatus')) {
        record.pendingStatus = false;
      }
      // jsx写法
      return (
        <>
          {record.goods.map((goods) => (
            <GoodsItem goods={goods} />
          ))}
        </>
      );
    },
  },
  {
    title: '实付款',
    dataIndex: 'total_price',
    width: 80,
    align: 'left',
    slots: { title: 'customPrice', customRender: 'price' },
    customRender: ({ record }) => {
      if (!Reflect.has(record, 'pendingStatus')) {
        record.pendingStatus = false;
      }
      // const style={fontSize:'12px'}
      // TODO 使用 white-space 这里会报错 但移除效果就会消失
      // const style={'white-space':'pre-line'}
      // return <div style={style} >{`￥${record.total_price}\n(含运费：￥${record.express_price})`}</div>
      return h(
        'div',
        {
          style: {
            whiteSpace: 'pre-line',
          },
        },
        `￥${record.pay_price}\n(含运费：￥${record.express_price})`,
      );
    },
  },
  {
    title: '买家',
    dataIndex: 'user',
    width: 100,
    align: 'left',
    slots: { title: 'customUser', customRender: 'user' },
    customRender: ({ record }) => {
      if (!Reflect.has(record, 'pendingStatus')) {
        record.pendingStatus = false;
      }
      return <Buyer buyer={record.user} />;
      // return h(Buyer, {
      //   buyer: record.user,
      // });
    },
  },
  {
    title: '支付方式',
    dataIndex: 'role',
    width: 100,
    slots: { title: 'customPayType', customRender: 'PayType' },
    customRender: ({ record }) => {
      return (
        <Tag color={PayTypeColorEnum[record.pay_type].name}>
          {PayTypeEnum[record.pay_type].name}
        </Tag>
      );
    },
  },
  {
    title: '配送方式',
    dataIndex: 'delivery_type',
    width: 100,
    slots: { title: 'customDeliveryType', customRender: 'deliveryType' },
    customRender: ({ record }) => {
      return <Tag>{record.delivery_text}</Tag>;
    },
  },
  // 交易状态有点乱
  {
    title: '交易状态',
    dataIndex: 'order_status',
    width: 150,
    align: 'left',
    slots: { title: 'customStatus', customRender: 'status' },
    customRender: ({ record }) => {
      if (!Reflect.has(record, 'pendingStatus')) {
        record.pendingStatus = false;
      }

      const {
        pay_status,
        delivery_type,
        delivery_status,
        receipt_status,
        delivery_time,
        order_status,
        is_print,
      } = record;
      const handle = (e) => {
        e.stopPropagation()
        updatePrint({
          orderId: record.order_id,
        }).then(() => {
          reload();
        });
        
      };

      // 打印小票
      const printColor = is_print ? 'green' : 'red';
      const printText = is_print ? '已打印' : '未打印';
      const PrintTag = () => (
        <Popconfirm
          title={<p>是否确定已经打印小票</p>}
          
          placement="top"
          ok-text="确定"
          cancel-text="取消"
          onConfirm={handle}
        >
          <Tag onClick={e=>e.stopPropagation()} color={printColor}>{printText}</Tag>
        </Popconfirm>
      );

      const PrintArr = ['\n小票打印：', PrintTag()];
      // 付款状态
      const payColor = pay_status == PayStatusEnum['SUCCESS'].value ? 'green' : '';
      const payText = PayStatusEnum[pay_status].name;
      const PayTag = () => <Tag color={payColor}>{payText}</Tag>;
      const payStatusArr = ['付款状态：', PayTag()];
      // 配送/发货 状态
      const isDelivery = delivery_type === DeliveryTypeEnum['THIRD'].value;
      const deliveryColor = isDelivery
        ? delivery_status === ThirdDeliverStatusEnum['COMPLETE'].value
          ? 'green'
          : ''
        : delivery_status == DeliveryStatusEnum['DELIVERED'].value
        ? 'green'
        : '';
      const deliveryText = isDelivery
        ? ThirdDeliverStatusEnum[delivery_status].name
        : DeliveryStatusEnum[delivery_status].name;
      const DeliveryTag = () => (
        <Tag style={{ marginTop: '5px' }} color={deliveryColor}>
          {deliveryText}
        </Tag>
      );

      const showDelivery =
        delivery_type !== DeliveryTypeEnum['PICKUP'].value &&
        pay_status !== OrderStatusEnum['CANCELLED'].value;
      const deliveryTitle =
        delivery_type === DeliveryTypeEnum['THIRD'].value ? '配送状态' : '发货状态';
      const deliveryStatusArr = showDelivery ? [`\n${deliveryTitle}：`, DeliveryTag()] : [];
      // 收货状态
      const receiptColor = receipt_status == ReceiptStatusEnum['RECEIVED'].value ? 'green' : '';
      const receiptText = PayStatusEnum[pay_status].name;
      const ReceiptTag = () => (
        <Tag style={{ marginTop: '5px' }} color={receiptColor}>
          {receiptText}
        </Tag>
      );

      const showReceipt =
        delivery_type !== DeliveryTypeEnum['PICKUP'].value &&
        pay_status !== OrderStatusEnum['CANCELLED'].value;
      const receiptStatusArr = showReceipt ? ['\n收货状态：', ReceiptTag()] : [];

      // 订单状态
      const orderStatusColor = {
        [OrderStatusEnum['NORMAL'].value]: '',
        [OrderStatusEnum['CANCELLED'].value]: 'red',
        [OrderStatusEnum['APPLY_CANCEL'].value]: 'red',
        [OrderStatusEnum['COMPLETED'].value]: 'green',
      };
      const OrderTag = () => (
        <Tag
          style={{ marginTop: '5px', marginBottom: '5px' }}
          color={orderStatusColor[order_status]}
        >
          {OrderStatusEnum[order_status].name}
        </Tag>
      );

      const orderStatusArr = ['\n订单状态：', OrderTag()];
      // 判断状态内容 由于whiteSpace 用在 jsx上的style会类型检查出错，所以暂时使用h方式的方式展示
      return h(
        'div',
        {
          style: {
            whiteSpace: 'pre-line'
          },
        },
        [
          ...payStatusArr,
          ...deliveryStatusArr,
          ...receiptStatusArr,
          ...orderStatusArr,
          ...PrintArr,
          `\n预约时间：${delivery_time || '立即'}`,
        ],
      );
    },
  },
  {
    title: '创建时间',
    dataIndex: 'create_time',
    width: 100,
  },
];

// 表格搜索类型
const allType = { value: -1, label: '全部' };
// 通过枚举获取选择框的值
const getTypeByEnum = (data) =>
  data.data.map((v) => {
    return {
      label: v.name,
      ...v,
    };
  });

export const SearchType = [
  { label: '订单号', value: 10 },
  { label: '会员昵称', value: 20 },
  { label: '会员ID', value: 30 },
];

export let tabs = [
  {
    label: '全部订单',
    value: 'all',
  },
  {
    label: '待发货',
    value: 'delivery',
  },
  {
    label: '待接单',
    value: 'waiting',
  },
  {
    label: '取货中',
    value: 'pickup',
  },
  {
    label: '配送中',
    value: 'distribution',
  },
  {
    label: '待收货',
    value: 'receipt',
  },
  {
    label: '待付款',
    value: 'pay',
  },
  {
    label: '已完成',
    value: 'complete',
  },
  {
    label: '已取消',
    value: 'cancel',
  },
];

const getStoreInfo = async () => {
  const data = await storeDetail();
  const {
    storeInfo: { is_o2o },
  } = data;
  const o2oKeys = ['pickup', 'distribution'];
  tabs = is_o2o
    ? tabs.filter((v) => v.value !== 'receipt')
    : tabs.filter((v) => !o2oKeys.includes(v.value));
};

getStoreInfo();
// 表格搜索框
export const searchFormSchema: FormSchema[] = [
  {
    field: 'dataType',
    label: '',
    defaultValue: 'all',
    component: 'Input',
    colProps: { span: 24, offset: 0 },
    // componentProps
    render: ({ model, field }) => {
      const onTabClick = (e: ChangeEvent) => {
        model[field] = e;
        reload();
      };
      return (
        <Tabs activeKey={model[field]} onTabClick={onTabClick}>
          {tabs.map((tab) => (
            <TabPane key={tab.value} tab={tab.label} />
          ))}
        </Tabs>
      );
    },
  },
  {
    field: 'searchType',
    label: '搜索类型',
    component: 'Input',
    labelWidth: 70,
    colProps: { span: 3 },
    defaultValue: 10,
    ifShow: false,

    slot: 'search',
  },
  {
    field: ' searchType',
    label: '关键字',
    component: 'Input',
    defaultValue: 10,
    labelWidth: 70,
    colProps: { span: 7 },
    render: ({ model, field }) => {
      const inputStyle = { display: 'flex', flexDirection: 'row' };
      const selectStyle = { width: '150px' };
      const inputKey = 'searchValue';
      // 组合输入框 TODO 需要给 searchType一个 默认值
      return (
        <InputGroup compact style={inputStyle}>
          <Select
            style={selectStyle}
            value={model[field]}
            options={SearchType}
            onChange={(e) => (model[field] = e)}
          >
            {model[field]}
          </Select>
          <Input
            value={model[inputKey]}
            placeholder="请输入关键字"
            onChange={(e) => (model[inputKey] = e.target.value)}
          />
        </InputGroup>
      );
    },
  },
  {
    field: 'orderSource',
    label: '订单来源',
    component: 'Select',
    defaultValue: -1,
    componentProps: ({ tableAction }) => {
      reload = tableAction.reload;
      return { options: [allType, ...getTypeByEnum(OrderSourceEnum)] };
    },
    labelWidth: 100,
    colProps: { span: 5 },
  },
  {
    field: 'payType',
    label: '支付方式',
    component: 'Select',
    defaultValue: -1,
    componentProps: {
      options: [allType, ...getTypeByEnum(PayTypeEnum)],
    },
    labelWidth: 100,
    colProps: { span: 5 },
  },
  {
    field: 'deliveryType',
    label: '配送方式',
    component: 'Select',
    defaultValue: -1,
    componentProps: {
      options: [allType, ...getTypeByEnum(DeliveryTypeEnum)],
    },
    labelWidth: 100,
    colProps: { span: 5 },
  },
  {
    field: 'betweenTime',
    label: '下单时间',
    component: 'RangePicker',
    componentProps: {
      dateFormatList: ['DD-MM-YYYY', 'DD-MM-YY'],
      valueFormat: 'DD-MM-YYYY',
    },
    labelWidth: 70,
    colProps: { span: 7 },
  },
];
